﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Net.Sockets;
using BomberManServer.Gaming.Serialization.Object.Connection;
using BomberManServer.Gaming.Serialization.Object.Player;
using System.Runtime.InteropServices;

namespace BomberManServer.Gaming.Serialization
{
    // usefull class to serialize objects
    public class Serializer
    {
        public void DeSerialize<T>(Stream stream, out T item)
        {
            // look at the stream size
            int rawsize = Marshal.SizeOf(typeof(T));
            /*
            if (rawsize > stream.Length)
                item = default(T);
             * */

            // extract data from the stream
            byte[] rawData = new byte[rawsize];
            if (stream.Read(rawData, 0, rawsize) != rawsize)
                item = default(T);

            // copy data in the object
            IntPtr buffer = Marshal.AllocHGlobal(rawsize);
            Marshal.Copy(rawData, 0, buffer, rawsize);
            T obj = (T)Marshal.PtrToStructure(buffer, typeof(T));
            Marshal.FreeHGlobal(buffer);
            item = obj;
        }

        public void Serialize<T>(Stream stream, T item)
        {
            int rawSize = Marshal.SizeOf(typeof(T));
            IntPtr buffer = Marshal.AllocHGlobal(rawSize);
            Marshal.StructureToPtr(item, buffer, false);
            byte[] rawData = new byte[rawSize];
            Marshal.Copy(buffer, rawData, 0, rawSize);
            Marshal.FreeHGlobal(buffer);
            stream.Write(rawData, 0, rawData.Length);
        }

        public void Serialize(Stream stream,string data)
        {
            int count = Encoding.UTF8.GetByteCount(data);
            stream.Write(BitConverter.GetBytes(Convert.ToUInt16(count)),0,2);
            stream.Write(Encoding.UTF8.GetBytes(data),0,count);
        }
    }
}
